<template>
  <div class="app-container empList">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <dataTree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            :default-expanded-keys="treeExpandData"
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-row style="margin: auto; width: 100%; text-align: center; height: 37px;">
            <h1 style="display: inline-block; margin-top: -4px; text-align: center; color: #8b836c; font-size: 1.5rem; letter-spacing: 1px; font-family: serif;">员工列表</h1>
        </el-row>
        <el-form :model="queryParam" ref="queryForm" :inline="true" style="text-align: center;">
          <el-row style="transform: scale(0.9)">
            <el-form-item label="员工姓名：" class="empNm">
              <!-- <el-input v-model="queryParam.userName" ></el-input> -->
              <el-select v-model="queryParam.userName" filterable placeholder="选择（或输入）员工姓名" clearable>
                <el-option
                  v-for="item in relaEmpList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                  :title="item.name">
                  <span>{{ item.name }}</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="状态：" class="empStatus">
              <el-select v-model="queryParam.status" placeholder="员工状态" clearable>
                <el-option v-for="item in empStatus" :key="item.key" :value="item.key"
                          :label="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间：">
              <!-- <el-date-picker v-model="queryParam.createTimeArr" value-format="yyyy-MM-dd" type="datetimerange" -->
              <el-date-picker v-model="queryParam.createTimeArr" value-format="yyyy-MM-dd" type="daterange"
                              range-separator="至" start-placeholder="起始时间" end-placeholder="结束时间">
              </el-date-picker>
            </el-form-item>
          </el-row>

          <el-form :model="queryParam" ref="queryForm" :inline="true" style="text-align: center;">
            <el-form-item class="btn">
              <el-button class="resetBtn" size="small"  style="margin-left: 15px" @click="resetForm">重置</el-button>
              <el-button class="detailBtn" size="small" style="margin-left: 15px" @click="syncQYWECHAT">从企业微信同步数据</el-button>
              <el-button class="add2Btn" size="small"  style="margin-left: 15px" @click="handleExport">导出</el-button>
              <el-button class="qryBtn" size="small"  style="margin-left: 15px" @click="submitForm">查询</el-button>
            </el-form-item>

            <!-- <el-form-item>
            </el-form-item> -->
          </el-form>

          <el-form :inline="true" style="text-align: center; display:  flex; flex-direction: column; justify-content: center; align-items: center;">
            <el-table
              v-loading="listLoading"
              :data="tableData"
              fit 
              highlight-current-row
              style="
                width: 99.2%;
                border: 1px solid rgb(220, 223, 230);
                margin-bottom: 12px;
                margin-top: -8px;
                border-radius: 10px;
                over-flow: auto;
              "
              max-height="350px"
              :header-cell-style="{
                'color':'#ffffff',
                'border-bottom-radius': '1px',
                'font-size':'0.86rem',
                'height':'8px',
                'font-family': 'serif',
                'font-weight': '800',
                'background': '#a2997f',
                'border-right-color': '#b6b6b1',
                'border-bottom-color': '#b6b6b1',
                'border-width': '1.2px'
              }"
              border
            >
              <el-table-column prop="id" label="编号"  min-width="8%" />
              <el-table-column prop="userName" label="用户姓名"  min-width="10%" />
              <el-table-column prop="departs" label="归属部门"   min-width="40%" />
              <el-table-column prop="credit" label="积分"  min-width="10%" />
              <!-- <el-table-column prop="sex" label="性别" width="60px;" :formatter="sexFormatter"/> -->
              <!-- <el-table-column prop="phone" label="手机号"/> -->
              <el-table-column label="状态" prop="status" min-width="8%" >
                <!-- <template slot-scope="{row}">
                  <el-tag :type="statusTagFormatter(row.status)">
                    {{ statusFormatter(row.status) }}
                  </el-tag>
                </template> -->
                <template slot-scope="{row}">
                  <el-switch
                    v-model="row.status"
                    active-color="#bdb398"
                    inactive-color="#d4d4d4"
                    :active-value='1'
                    :inactive-value='2'
                    @change="transSta(row)"
                  >
                  </el-switch>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="创建时间"  min-width="20%" />
              <!-- <el-table-column width="270px" label="操作" align="center">
                <template slot-scope="{row}">
                  <el-button size="mini"  @click="changeStatus(row)" class="link-left">
                    {{ statusBtnFormatter(row.status) }}
                  </el-button>
                  <router-link :to="{path:'/user/student/edit', query:{id:row.id}}" class="link-left">
                    <el-button size="mini" >编辑</el-button>
                  </router-link>
                  <router-link :to="{path:'/log/user/list', query:{userId:row.id}}" class="link-left">
                    <el-button size="mini" >日志</el-button>
                  </router-link>
                  <el-button  size="mini" type="danger" @click="deleteUser(row)" class="link-left">删除</el-button>
                </template>
              </el-table-column> -->
            </el-table>

            <!--  layout="prev, pager, next, jumper" -->
            <pagination v-show="total>0" :total="total" :page.sync="queryParam.pageNum" :limit.sync="queryParam.pageSize"
              @pagination="search"/>
          </el-form>
        </el-form>
      </el-col>
    </el-row>

  </div>
</template>

<script>
import { mapGetters, mapState } from 'vuex'
import Pagination from '@/components/Pagination'
import userApi from '@/api/user'
import deptApi from '@/api/dept'
import dataTree from '@/components/tree/src/tree.vue'

export default {
  components: { Pagination, dataTree },
  data () {
    return {
      treeExpandData: [],
      relaEmpList: [],
      // 部门名称
      deptName: undefined,
      // 部门树选项
      deptOptions: undefined,
      defaultProps: {
        children: "children",
        label: "label"
      },
      empStatus: [
        {
          key: '1',
          value: '启用'
        },
        {
          key: '2',
          value: '禁用'
        }
      ],
      syncParam: {
        useCache: false
      },
      queryParam: {
        userName: '',
        status: '',
        deptId: null,
        beginTime: '',
        endTime: '',
        createTimeArr: [],
        pageNum: 1,
        pageSize: 10
      },
      listLoading: true,
      tableData: [],
      total: 0
    }
  },
  created () {
    userApi.userFilter().then(res => {
      this.relaEmpList = res.response
    })
    this.search()
    this.getDeptTree();
  },
  methods: {
    handleExport () {
      userApi.exportUserlist(this.queryParam).then(() => {
      })
    },
    getRoleTreeRootNode(res) {
      this.treeExpandData.push(res[0].id)      
    },
    transSta(row) {
      let _this = this
      const beforeSta = row.status
      let params = { id: row.id, status: row.status }
      userApi.updateStatus(params).then(res => {
        if (res.code === 1) {

          this.search()

          if (row.status == 1) {
            _this.$message.success('用户已启用！')
          } else {
            _this.$message.warning('用户已禁用！')
          }
        } else {
          _this.$message.error(res.message)
          this.search()
        }
      }).catch(err =>  {
        console.log('error:', err)
        _this.search()
      }).finally(() => {
        this.search()
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptApi.getDeptList().then(data => {
        const re = data.response
        if (data.code == 1) {
          this.deptOptions = [re]
          this.getRoleTreeRootNode([re])
        } else {
          this.$message({
            type: 'warning',
            message: '获取部门树失败，可刷新页面重试！'
          })
          this.listLoading = false
          return
        }
        this.listLoading = false
      })
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParam.deptId = data.id;
      this.search();
    },
    syncQYWECHAT () {
      this.listLoading = true
      this.$modal.loading('同步中，请稍候...')
      userApi.syncQYWX(this.syncParam).then(data => {
        const re = data.response
        if (data.code == 1) {
          this.$modal.msgSuccess('员工数据同步成功！')
          this.search()
        } else {
          this.$modal.msgWarning('从企业微信同步更新数据失败，请稍后重试！')
          this.$modal.closeLoading()
          this.listLoading = false
          return
        }
        this.$modal.closeLoading()
        this.listLoading = false
      })
    },
    search () {
      this.listLoading = true
      if (this.queryParam.createTimeArr.length > 0) {
        this.queryParam.beginTime = this.queryParam.createTimeArr[0]
        this.queryParam.endTime = this.queryParam.createTimeArr[1]
      }
      userApi.getUserList(this.queryParam).then(data => {
        const re = data.response
        this.tableData = re.list
        this.total = re.total
        this.queryParam.pageNum = re.pageNum
        this.listLoading = false
      })
    },
    changeStatus (row) {
      let _this = this
      userApi.changeStatus(row.id).then(re => {
        if (re.code === 1) {
          row.status = re.response
          _this.$message.success(re.message)
        } else {
          _this.$message.error(re.message)
        }
      })
    },
    deleteUser (row) {
      let _this = this
      userApi.deleteUser(row.id).then(re => {
        if (re.code === 1) {
          _this.search()
          _this.$message.success(re.message)
        } else {
          _this.$message.error(re.message)
        }
      })
    },
    resetForm() {
      this.queryParam = {
        userName: '',
        role: 1,
        status: '',
        deptId: undefined,
        beginTime: '',
        endTime: '',
        createTimeArr: [],
        pageNum: 1,
        pageSize: 10
      }
      this.getDeptTree()
      this.search()
    },
    submitForm () {
      this.queryParam.pageNum = 1
      this.search()
    },
    levelFormatter  (row, column, cellValue, index) {
      return this.enumFormat(this.levelEnum, cellValue)
    },
    sexFormatter  (row, column, cellValue, index) {
      return this.enumFormat(this.sexEnum, cellValue)
    },
    statusFormatter (status) {
      return this.enumFormat(this.statusEnum, status)
    },
    statusTagFormatter (status) {
      return this.enumFormat(this.statusTag, status)
    },
    statusBtnFormatter (status) {
      return this.enumFormat(this.statusBtn, status)
    }
  },
  computed: {
    ...mapGetters('enumItem', [
      'enumFormat'
    ]),
    ...mapState('enumItem', {
      sexEnum: state => state.user.sexEnum,
      statusEnum: state => state.user.statusEnum,
      statusTag: state => state.user.statusTag,
      statusBtn: state => state.user.statusBtn,
      levelEnum: state => state.user.levelEnum
    })
  }
}
</script>

<style rel="stylesheet/scss" lang='scss'>
  .empList {
    padding: 30px;
  }

  .empList .empNm .el-input--medium .el-input__inner {
    height: 36px;
    line-height: 36px;
    width: 143px;
  }


  .empList .empStatus .el-input--medium .el-input__inner {
    height: 36px;
    line-height: 36px;
    width: 143px;
  }

  .empList .el-form--inline .el-form-item {
    display: inline-block;
    margin-right: 10px;
    vertical-align: top;
    margin-left: 12px;
    margin-bottom: 11px;
  }

  .empList .el-form--inline .btn {
    display: inline-block;
    margin-right: 10px;
    vertical-align: top;
    margin-left: 12px;
    margin-bottom: 21px;
  }

  .empList .el-form-item__label {
    text-align: right;
    vertical-align: middle;
    float: left;
    font-size: 14px;
    color: #606266;
    line-height: 40px;
    padding: 0 2px 0 0;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
  }

  .empList .el-pagination {
    white-space: nowrap;
    padding: 2px 5px;
    color: #303133;
    font-weight: bold;
    text-align: center;
  }

  .empList .el-date-editor .el-range-separator {
    display: inline-block;
    height: 100%;
    padding: 0 5px;
    margin: 0;
    text-align: center;
    line-height: 32px;
    font-size: 14px;
    width: 6%;
    color: #303133;
  }

  .empList .el-tree-node__label {
    font-size: 0.9rem;
  }

  .empList .el-tree--highlight-current
  .el-tree-node.is-current
  > .el-tree-node__content {
    background-color: rgba(135, 206, 235, 0.2); // 透明度为0.2的skyblue，作者比较喜欢的颜色
    color: #409eff;
    font-weight: bold;
    width: 128%;
  }


  .empList .el-form-item__error {
    color: #ff4949;
    font-size: 12px;
    line-height: 1;
    padding-top: 0px;
    position: absolute;
    top: 100%;
    left: 0;
  }

  .empList .el-table .cell {
    text-align: center;
  }

</style>
